/* eslint indent: ["off"] */
/* eslint space-before-function-paren: ["off"] */

// 引入 lodash 库，用于数据处理和操作
const _ = require('lodash')
// 引入 fs 模块，用于文件系统操作
const fs = require('fs')
// 引入 path 模块，用于处理文件和目录路径
const path = require('path')
// 引入 esm 库，用于在 Node.js 中支持 ES6 模块
const esm = require('esm')
// 使用 esm 配置来加载模块
const requireModule = esm(module)

// 桌面通知
const notifier = require('node-notifier')

// 地区
const { region } = requireModule(path.join(__dirname, '../src/utils/modules/settings.js'))

// 获取项目根目录
const ROOT_DIR = path.join(__dirname, '..')
// helpers 目录
const HELPERS_DIR = path.join(ROOT_DIR, 'helpers')
// 读取并构建 fixedGroupMapObject
const { finalGroupMap, flatGroupMap, groupArray } = requireModule(path.join(HELPERS_DIR, 'readGroup.js'))

// 计算准确统计
const { calcAccuracySummary, ACCURACY_SUMMARY_CN_MAP } = require(path.join(HELPERS_DIR, 'calcAccuracySummary.js'))
// 获取窗口准确列表
const getWindowAccuracyMap = require(path.join(HELPERS_DIR, 'getWindowAccuracyMap.js'))

// 获取下一个大写字母
const getNextLetter = require(path.join(HELPERS_DIR, 'getNextLetter.js'))

// 读取所有数据
const { readAllValues } = require(path.join(HELPERS_DIR, 'readAllValues.js'))

const allValues = readAllValues(region)
  // .slice(0, 200)
  // .slice(0, 220)
  // .slice(0, 400)
  // .slice(0, 500)
  // .slice(0, 600)
// .slice(0, 1000)

console.log('allValues.length', allValues.length)

console.time('计算结束')

const allNumbers = Array.from({ length: 49 }, (_, i) => i + 1).map((num) => (num < 10 ? `0${num}` : `${num}`))

// console.log(allNumbers)
// console.log(flatGroupMap)
fs.writeFileSync(path.join(__dirname, 'json/flatGroupMap.json'), JSON.stringify(flatGroupMap, null, 2), 'utf8')
fs.writeFileSync(path.join(__dirname, 'json/groupArray.json'), JSON.stringify(groupArray, null, 2), 'utf8')

// 初始化目标对象，每个数字对应空对象
const numberGroupMap = allNumbers.reduce((acc, num) => {
  acc[num] = {}
  return acc
}, {})

// 初始化每个Number在不同分组中的索引
Object.entries(flatGroupMap).forEach(([groupName, groups]) => {
  // groups是包含两个子数组的数组
  groups.forEach((group, groupIndex) => {
    group.forEach((num) => {
      // 将数字转为两位字符串，如2 -> '02'
      const numStr = num.toString().padStart(2, '0')
      // 确保该数字在映射中存在
      if (numberGroupMap[numStr]) {
        // 将分组名称和子数组索引存入
        numberGroupMap[numStr][groupName] = groupIndex
      }
    })
  })
})

const getDefaultR1Map = () => {
  return _.mapValues(flatGroupMap, (value, key) => {
    return {
      accuracyList: [],
      group_type: undefined
    }
  })
}

// 过滤A
const handleFilterGroupsA = require('./algorithms/handleFilterGroupsA.js')
// 过滤A
const handleFilterGroupsB = require('./algorithms/handleFilterGroupsB.js')

// 排序A
// const handleOrderGroupsA = require('./algorithms/handleOrderGroupsA.js')

// 选号A
const getLucky = require(path.join(HELPERS_DIR, 'getLucky.js'))

// 公共过滤
// const handleFilterGroupsCommon = require('./algorithms/handleFilterGroupsCommon.js')
// 公共排序
const handleOrderGroupsCommon = require('./algorithms/handleOrderGroupsCommon.js')

// todo write file
//*

let emptyFilteredGroupsCount = 0

const windowSize = 200

const data = allValues.map((item, index) => {
  if (index % 50 === 0) {
    console.log('正在处理', index, '条数据')
  }
  if (index < windowSize) {
    return {
      ...item,
      lucky_array: [],
      kill_array: [],
      kill_group_names: []
    }
  } else {
    const windowList = allValues.slice(index - windowSize - 1, index + 1)
    const r1 = getWindowAccuracyMap(getDefaultR1Map(), windowList, groupArray, flatGroupMap, numberGroupMap)

    const currentGroupArray = _.chain(r1)
      .mapValues((value, key) => {
        const currentAccuracyList = value.accuracyList.slice(index - windowSize - 1, index + 1)
        // 计算准确率
        const stats = calcAccuracySummary(currentAccuracyList)
        return {
          groupName: key,
          groupType: value.group_type,
          accuracy_array: currentAccuracyList,
          stats
        }
      })
      .values()
      .value()
    // 过滤
    const filteredGroupsA = handleFilterGroupsA(currentGroupArray)
    const filteredGroupsB = handleFilterGroupsB(currentGroupArray)

    // if (!filteredGroupsA.length) {
    //   // console.log('filteredGroupsA.length', filteredGroupsA.length)
    //   console.log('emptyFilteredGroupsCount', ++emptyFilteredGroupsCount)
    // }

    // todo 排序 暂无使用
    // const orderedGroupsA = handleOrderGroupsA(filteredGroupsA)
    const orderedGroupsA = filteredGroupsA
    const orderedGroupsB = filteredGroupsB

    // 选号
    const calcA = getLucky(orderedGroupsA, item, numberGroupMap, flatGroupMap)
    const calcB = getLucky(orderedGroupsB, item, numberGroupMap, flatGroupMap)

    if (calcA.lucky_array.length < 32) {
      return {
        ...item
      }
    } else {
      // console.log(`${item.time} rules: 'A' ${Object.keys(calcA)}`)
      return {
        ...item,
        calcA,
        calcB,
        rules: 'A'
      }
    }
  }
})

// eslint-disable-next-line no-irregular-whitespace
fs.writeFileSync(path.join(__dirname, `json/​${region}-Steps-08-data.json`), JSON.stringify(data, null, 2), 'utf8')

// 判断号码是否在 lucky_array 中
function checkAccuracy(lucky_array, number) {
  return lucky_array.map((item) => item.toString().padStart(2, '0')).includes(number.toString().padStart(2, '0'))
    ? 1
    : 0
}

// 获取上一期计算数据
function getCalcData(rules, prevData) {
  return rules ? prevData[`calc${rules}`] : null
}

// 处理规则冲突，生成新的规则并计算
function handleRuleConflict(prev_rules, prev_calc_data, item) {
  const temp_rules = getNextLetter(prev_rules)
  const temp_calc_data = temp_rules ? prev_calc_data[temp_rules] : null

  if (temp_calc_data) {
    const temp_accuracy = checkAccuracy(temp_calc_data.lucky_array, item.number)
    console.log(`${item.time} temp_accuracy: ${temp_accuracy}`)

    return {
      ...item,
      accuracy: temp_accuracy
    }
  } else {
    return {
      ...item,
      accuracy: undefined
    }
  }
}

const allList = data.map((item, index) => {
  if (index < 3) {
    return {
      ...item,
      accuracy: 1
    }
  } else {
    // 主逻辑开始
    const prev = data[index - 1]
    const prev2 = data[index - 2]

    const prev_rules = prev?.rules
    const prev2_rules = prev2?.rules

    const prev_calc_data = getCalcData(prev_rules, prev)
    const prev2_calc_data = getCalcData(prev2_rules, prev2)

    if (prev2_calc_data && prev2_calc_data.lucky_array.length) {
      const prevAccuracy = checkAccuracy(prev2_calc_data.lucky_array, prev.number)

      // 处理规则冲突的逻辑
      if (prevAccuracy === 0 && prev2_calc_data.kill_group_names[0] === prev_calc_data.kill_group_names[0]) {
        return handleRuleConflict(prev_rules, prev, item)
      } else {
        // 没有规则冲突，直接计算当前准确率
        if (prev_calc_data && prev_calc_data.lucky_array.length) {
          const accuracy = checkAccuracy(prev_calc_data.lucky_array, item.number)
          return {
            ...item,
            accuracy
          }
        } else {
          return {
            ...item,
            accuracy: undefined
          }
        }
      }
    } else {
      // 如果 prev2_calc_data 没有数据，继续检查 prev_calc_data
      if (prev_calc_data && prev_calc_data.lucky_array.length) {
        const accuracy = checkAccuracy(prev_calc_data.lucky_array, item.number)
        return {
          ...item,
          accuracy
        }
      } else {
        return {
          ...item,
          accuracy: undefined
        }
      }
    }
  }
})

// eslint-disable-next-line no-irregular-whitespace
fs.writeFileSync(
  path.join(__dirname, `json/​${region}-Steps-09-allList.json`),
  JSON.stringify(allList, null, 2),
  'utf8'
)

// eslint-disable-next-line spaced-comment
//*/

// todo read file
//*

// eslint-disable-next-line no-irregular-whitespace
fs.readFile(path.join(__dirname, `json/​${region}-Steps-09-allList.json`), 'utf8', (err, jsonString) => {
  if (err) {
    console.error('读取文件失败:', err)
    return
  }
  try {
    const data = JSON.parse(jsonString)
    const accuracyList = data
      .filter((item) => {
        if (item === null) {
          console.log(`${item.time}`)
        }
        return item.accuracy === 1 || item.accuracy === 0
      })
      .map((item) => item.accuracy)
    const accuracySummary = calcAccuracySummary(accuracyList)
    // 打印中文
    Object.entries(ACCURACY_SUMMARY_CN_MAP).forEach(([key, value]) => {
      console.log(`${value}: ${accuracySummary[key]}`)
    })

    console.timeEnd('计算结束')

    notifier.notify({
      title: '哥们看看',
      icon: path.join(__dirname, 'cat.png'),
      message: '计算结束'
    })
  } catch (parseErr) {
    console.error('解析 JSON 失败:', parseErr)
  }
})

// eslint-disable-next-line spaced-comment
//*/
